import Taro from '@tarojs/taro';

import {
  Command,
  GAME_TYPE,
  IMAGE_EMPTY,
  CARD_CUONT,
  APPELLATION_COUNT,
  GAME_STORAGE_INFO,
  CODE_SUCCESS,
} from '../constant';
import {Dispatch} from 'typings';
import {IAllReducerProps, StateCommonType, ComputeItems} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';

import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    async status() {
      // 或取当前状态值
      let {
        main: {isLoading},
      } = getData();
      action.commonChange('main.isLoading', !isLoading);
    },

    /**
     * state值更新
     * @param payload
     */
    async stateCommonChange(payload: StateCommonType) {
      const {stateName, value} = payload;
      action.commonChange(stateName, value);
    },

    /**
     * 查询游戏次数
     * @param payload
     */
    async loadGameTimes(payload) {
      console.log('action.ts loadGameTimes payload', payload);

      action.commonChange('main.response.loadGameTimes', '');
      action.commonChange('main.status.loadingGameTimes', true);

      // 编辑参数
      let params = {
        gameType: GAME_TYPE,
        ...payload,
      };

      let {data, code, message} = await api.SyntheticCardController.getGameTimesConfigInfo(params);
      console.log('index.tsx getGameTimes data', data);

      let {
        main: {userInfo},
      } = getData();

      userInfo = {
        ...userInfo,
        gameAvailableTimes: data || 0,
      };

      action.commonChange('main.userInfo', userInfo);
      action.commonChange('main.response.loadGameTimes', code);
      action.commonChange('main.status.loadingGameTimes', false);
    },

    /**
     * 称号列表初始化数据
     */
    appellactionItemsInit(total) {
      let items = [];
      let length = total ? total : APPELLATION_COUNT;
      for (let i = 0; i < length; i++) {
        items.push({
          id: 'no' + i,
          obtainFlag: false,
          imgUrl: IMAGE_EMPTY,
          prizeName: '',
          type: 'empty',
          prizeType: '',
        });
      }
      return items;
    },

    /**
     * 查询ip称号商品列表
     * @param payload
     */
    async loadAppellationItems(payload) {
      let {
        main: {appellationItems},
      } = getData();

      let items = action.appellactionItemsInit(appellationItems.length);

      action.commonChange('main.appellationItems', items);
      action.commonChange('main.response.loadAppellation', '');
      action.commonChange('main.status.loadingAppellation', true);

      // 编辑参数
      let params = {
        ...payload,
      };
      console.log('action.ts synthetiCard loadAppllationItems params', params);

      let {data, code, message} = await api.SyntheticCardController.getAppellationItems(params);
      console.log('synthetciCard loadAppellationItems data', data);

      if (data.length == 0 || !data) {
        data = action.appellactionItemsInit(0);
      }

      action.commonChange('main.appellationItems', data);
      action.commonChange('main.response.loadAppellation', code);
      action.commonChange('main.status.loadingAppellation', false);
    },

    /**
     * 卡片初始化
     */
    cardItemsInit(data) {
      let items = [];
      for (let i = 0; i < CARD_CUONT; i++) {
        items.push({
          cardId: 'no' + i,
          carNum: 0,
          imgUrl: IMAGE_EMPTY,
          cardName: '',
          type: 'empty',
        });
      }
      return items;
    },

    /**
     * 查询卡片列表
     * @param payload
     */
    async loadCardItems(payload) {
      console.log('action.tsx loadCartItem');

      // 初始化卡片列表
      let items = action.cardItemsInit([]);

      action.commonChange('main.cardItems', items);
      action.commonChange('main.response.loadCard', '');
      action.commonChange('main.status.loadingCard', true);

      let {data, code, message} = await api.SyntheticCardController.getCardItems(payload);
      console.log('actin.ts loadCardItems data', data);

      if (data.length == 0 || !data) {
        data = action.cardItemsInit(data);
      }

      action.commonChange('main.cardItems', data);
      action.commonChange('main.response.loadIp', code);
      action.commonChange('main.status.loadingCard', false);
    },

    /**
     * 查询用户信息
     */
    async loadUserInfo(payload) {
      action.commonChange('main.userInfo', {});
      action.commonChange('main.response.loadUser', '');
      action.commonChange('main.status.loadingUser', true);

      let {data, code, message} = await api.customerBaseController.findCustomerBaseInfoForGame({});
      let userInfo: any = data || null;
      if (!userInfo) {
        userInfo = Taro.getStorageSync(GAME_STORAGE_INFO);
      }
      let accountType = '';
      if (userInfo && userInfo.customerName) {
        // 判断是否是会员
        if (!userInfo.isAquamarineMember && !userInfo.isCrystalMember) {
          accountType = '';
        } else if (userInfo.isAquamarineMember && userInfo.isCrystalMember) {
          accountType = 'isAquamarineMember&isCrystalMember';
        } else {
          accountType = userInfo.isAquamarineMember ? 'isAquamarineMember' : 'isCrystalMember';
        }
      }
      let userInfoInfo = getData().main.userInfo;
      userInfo = {
        ...userInfo,
        ...userInfoInfo,
        accountType,
      };
      action.loadGameTimes({}); // 用户剩余游戏次数
      action.loadGameDailyTimes(); // 当天剩余游戏次数
      action.commonChange('main.userInfo', {
        ...userInfo,
      });
      action.commonChange('main.response.loadUser', code);
      action.commonChange('main.status.loadingUser', false);
    },

    /**
     * 查询当日游戏次数
     */
    async loadGameDailyTimes() {
      action.commonChange('main.response.loadGameDailyTimes', '');
      action.commonChange('main.status.loadingGameDailyTimes', true);

      // 编辑参数
      let payload = {
        gameType: GAME_TYPE,
      };

      let {data, code, message} = await api.iplandBaseController.getGameDailyTimes(payload);
      console.log('syntheticCard loadGameDailyTimes data', data);

      let {
        main: {userInfo},
      } = getData();

      userInfo = {
        ...userInfo,
        userDailyTimes: data || 0,
      };
      action.commonChange('main.userInfo', userInfo);
      action.commonChange('main.response.loadGameDailyTimes', code);
      action.commonChange('main.status.loadingGameDailyTimes', false);
    },

    /**
     * 合成集卡
     */
    async syntheticCard(payload) {
      // 集卡中
      action.commonChange('main.codeMessage', '');
      action.commonChange('main.syntheticResult', {});
      action.commonChange('main.response.synthetic', '');
      action.commonChange('main.status.syntheticing', true);

      let {data, code, message} = await api.SyntheticCardController.cardSynthetic(payload);

      action.commonChange('main.codeMessage', message);
      action.commonChange('main.syntheticResult', data);
      action.commonChange('main.response.synthetic', code); // 模拟结果
      action.commonChange('main.status.syntheticing', false);
    },

    /**
     * 判断游戏是否可玩
     */
    async gamePlayingStatus(payload) {
      action.commonChange('main.gameInfo', {});
      action.commonChange('main.codeMessage', '');
      action.commonChange('main.response.play', '');
      action.commonChange('main.status.playing', true);

      // 编辑参数
      let params = {
        gameType: GAME_TYPE,
      };

      let {code, context, message} = await api.iplandBaseController.getGameBaseConfig(params);
      console.log('action gamePlayingStatus message=', message);

      let {
        main: {gameInfo},
      } = getData();

      gameInfo = {
        ...gameInfo,
        isPlay: code == CODE_SUCCESS ? context : false,
      };
      action.commonChange('main.gameInfo', gameInfo || {});
      action.commonChange('main.codeMessage', message);
      action.commonChange('main.response.play', code); // 模拟结果
      action.commonChange('main.status.syntheticing', false);
    },

    /**
     * 批量领取奖励（称号是商品）
     */
    async claimRewards(payload) {
      action.commonChange('main.response.claimRewards', '');
      action.commonChange('main.status.claimingRewards', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      // 编辑参数
      let {data, code, message} = await api.CatchPlaythingController.claimRewards(params);
      console.log('action.ts loadGameLottery res', data);

      action.commonChange('main.response.claimRewards', code);
      action.commonChange('main.status.claimingRewards', false);
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageSyntheticCardPaMain'),
  };
}
